package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.RedisConstant;
import com.dao.SetMealDao;
import com.entity.PageResult;
import com.entity.QueryPageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pojo.Setmeal;
import com.service.SetMealService;
import com.utils.PageDeleteUtils;
import com.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.JedisPool;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_file}")    //从属性文件中读取要生成html文件的相对目录
    private String outPutPath;

    @Override   //添加套餐 并关联套餐与检查组的多对多关系
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐
        setMealDao.add(setmeal);
        //关联套餐与检查组的多对多关系
        Integer setmealId = setmeal.getId();
        this.setSetMealAndCheckGroup(setmealId, checkgroupIds);
        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);

        //当添加套餐之后需要重新生成静态页面（套餐列表页面，套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前套餐所需要的静态界面
    public void generateMobileStaticHtml(){
        //当生成静态界面前需要查询所有数据
        List<Setmeal> list = setMealDao.findAll();
        //生成套餐列表界面
        generateMobileSetMealListHtml(list);
        //生成套餐详情界面
        generateMobileSetMealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetMealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能会有多个）
    public void generateMobileSetMealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map =new HashMap();
            map.put("setmeal",setMealDao.findByIds(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }

    //用于生产静态页面
    public void generateHtml(String templateName,String htmlPageName,Map map) {
        //获取配置对象
        Configuration configuration = freeMarkerConfig.getConfiguration();
        //创建write对象
        Writer out = null;
        try {
            //加载模块
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(outPutPath + "/" + htmlPageName);
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out){
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override   //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (queryString != null) {
            if (queryString.equals("null") || queryString.length() == 0) {
                queryString = "";
            } else {
                queryString = "%" + queryString + "%";
            }
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override  //通过id查询检查套餐
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupBySetMeal(Integer id) {
        return setMealDao.findCheckGroupBySetMeal(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //删除redis中原有的图片名称
        Setmeal setMealDaoById = setMealDao.findById(setmeal.getId());
        if (setMealDaoById.getImg() != null && setMealDaoById.getImg().length() > 0) {
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setMealDaoById.getImg());
            QiniuUtils.deleteFileFromQiniu(setMealDaoById.getImg());
        }
        //1.修改t_setmeal中的数据
        setMealDao.updateSetMeal(setmeal);

        String img = setmeal.getImg();
        if (img != null && img.length() > 0) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
        //2.删除t_setmeal_checkgroup 中有关该套餐id的数据
        setMealDao.deleteAssociation(setmeal.getId());
        //3.重新定义检查套餐与检查组的多对多数据
        Integer setmealId = setmeal.getId();
        this.setSetMealAndCheckGroup(setmealId, checkgroupIds);

        generateMobileStaticHtml();
    }

    @Override
    public void delete(Setmeal setmeal) {
        //1.删除套餐与检查组该id的对应关系
        setMealDao.deleteAssociation(setmeal.getId());
        //2.删除套餐
        setMealDao.delete(setmeal.getId());
        Setmeal setMealDaoById = setMealDao.findById(setmeal.getId());
        if (setMealDaoById.getImg() != null && setMealDaoById.getImg().length() > 0) {
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setMealDaoById.getImg());
            QiniuUtils.deleteFileFromQiniu(setMealDaoById.getImg());
        }
        Integer id = setmeal.getId();
        PageDeleteUtils.delete(outPutPath+"/setmeal_detail_"+id+".html");
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override   //根据套餐ID查询套餐详细信息（包括套餐基本信息、套餐包含的检查组、检查组包含的检查项）
    public Setmeal findByIds(Integer id) {
        return setMealDao.findByIds(id);
    }

    @Override   //查询套餐预约占比数据
    public List<Map<String, Object>> findSetMealCount() {
        return setMealDao.findSetMealCount();
    }

    public void setSetMealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }
}
